package com.eric.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import com.eric.domain.dto.CommonMaterialsDTO;
import com.eric.domain.po.CommonMaterials;
import com.eric.domain.vo.CommonMaterialsVO;
import com.eric.service.CommonMaterialsService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 *  控制层。
 *
 * @author eric.deng
 * @since 2025-03-05
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/commonMaterials")
public class CommonMaterialsController {


    private final CommonMaterialsService commonMaterialsService;

    //    添加一条新数据
    @PostMapping("save")
    public SaResult save(@Validated @RequestBody CommonMaterialsVO commonMaterialsVO) {
        return commonMaterialsService.saveOneService(commonMaterialsVO);
    }

    //    根据主键删除一条数据
    @DeleteMapping("remove/{id}")
    public SaResult remove(@PathVariable Long id) {
        if (id == null||id<=0) {
            return SaResult.data("数据错误");
        }
        return SaResult.data(commonMaterialsService.removeById(id));
    }

    //    更新一条数据
    @PutMapping("update")
    public SaResult update(@Validated @RequestBody CommonMaterialsVO commonMaterialsVO) {
        return commonMaterialsService.updateByIdService(commonMaterialsVO);
    }

    //    分页查询所有数据
    @GetMapping("list")
    public SaResult list(Integer cur, Integer pageSize) {
        return commonMaterialsService.getListByPageService(cur, pageSize);
    }

    //   查询所有数据的数量
    @GetMapping("/allCount")
    public SaResult getAllCount() {
        return SaResult.data(commonMaterialsService.count());
    }


    //   根据id查询一条数据详细信息
    @GetMapping("getInfo/{id}")
    public SaResult getInfo(@PathVariable Long id) {
        CommonMaterials commonMaterials = commonMaterialsService.getById(id);
        if (BeanUtil.isEmpty(commonMaterials)){
            return SaResult.error("没有数据");
        }
        CommonMaterialsDTO commonMaterialsDTO = BeanUtil.copyProperties(commonMaterials, CommonMaterialsDTO.class);

        return SaResult.data(commonMaterialsDTO);
    }

    //    根据名称查询
    @GetMapping("/getByName")
    public SaResult getByName(String name,Integer cur,Integer pageSize) {
        return commonMaterialsService.getCommonMaterialsListByNameService(name, cur, pageSize);
    }

    //    根据名称查询到数据的数量
    @GetMapping("/getByNameCount")
    public SaResult getByNameCount(String name) {
        return commonMaterialsService.getCommonMaterialsListByNameCountService(name);
    }


}
